package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.util.ExcelUtil;
import cn.stylefeng.guns.sys.modular.system.entity.BtySzgl;
import cn.stylefeng.guns.sys.modular.system.entity.ExcelExp;
import cn.stylefeng.guns.sys.modular.system.entity.TaskStatus;
import cn.stylefeng.guns.sys.modular.system.mapper.AreaMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.BtySzglMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.ProjectMapper;
import cn.stylefeng.guns.sys.modular.system.mapper.TaskStatusMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtySzglParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtySzglResult;
import  cn.stylefeng.guns.sys.modular.system.service.BtySzglService;
import cn.stylefeng.guns.sys.modular.system.service.BtyTxlService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * <p>
 * 双证管理 服务实现类
 * </p>
 *
 * @author yxc
 * @since 2022-03-16
 */
@Service
public class BtySzglServiceImpl extends ServiceImpl<BtySzglMapper, BtySzgl> implements BtySzglService {
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private BtyTxlService btyTxlService;
    @Autowired
    private TaskStatusMapper statusMapper;

    @Override
    public void add(BtySzglParam param){
        BtySzgl entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BtySzglParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(BtySzglParam param){
        //如果包含食品经营许可证等信息，修改状态为1
        if (ToolUtil.isNotEmpty(param.getSpjyxkz()) || ToolUtil.isNotEmpty(param.getYyzz())
                || ToolUtil.isNotEmpty(param.getFrCard())){
            param.setSta(1);
        }
        BtySzgl oldEntity = getOldEntity(param);
        BtySzgl newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);

        //同步法人和食品经营许可截止日期同步到安全基金和通讯录中
        List<Map> list = new ArrayList<>();
        Map map = new HashMap<>();
        if (ToolUtil.isNotEmpty(newEntity.getSpjyxkzrq())){
            map.put("spjyxkzrq",newEntity.getSpjyxkzrq());

            //同步到工程中
            if (ToolUtil.isNotEmpty(newEntity.getYaoma())){
                //查询pro_id
                Integer proId = projectMapper.getByYaoma(newEntity.getYaoma());
                if (ToolUtil.isNotEmpty(proId)){
                    TaskStatus status = new TaskStatus();
                    status.setProId(proId);
                    status.setTaskId(44);//卫生许可证截止日期
                    status.setContent(newEntity.getSpjyxkzrq());
                    statusMapper.updateStatus(status);
                }
            }

        }
        if (ToolUtil.isNotEmpty(newEntity.getYyzzfr())){
            map.put("yyzzfr",newEntity.getYyzzfr());
        }
        map.put("yaoma",newEntity.getYaoma());
        if (map.size() > 1){
            list.add(map);
            this.syncTxl(list);
        }
    }

    @Override
    public BtySzglResult findBySpec(BtySzglParam param){
        return null;
    }

    @Override
    public List<BtySzglResult> findListBySpec(BtySzglParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(BtySzglParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 导入excel
     * @param fileName
     * @param file
     * @return
     */
    @Override
    public Boolean batchImport(String fileName, MultipartFile file) throws Exception{

        boolean notNull = false;
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            throw new Exception("上传文件格式不正确");
        }

        boolean isExcel2003 = true;//Excel2003
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }

        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }

        //TODO-1 默认就一个sheet
        Sheet sheet = wb.getSheetAt(0);

        List<BtySzgl> list = new ArrayList();
        BtySzgl btySzgl = new BtySzgl();
        Long createUser = LoginContextHolder.getContext().getUserId();//创建者
        Date createTime = new Date();//创建时间

        //循环行row
        int lastRowNum = sheet.getLastRowNum();
        for (int r = 1; r <= lastRowNum; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            //循环单元格cell
            for (int cellNum = 0; cellNum <= row.getLastCellNum(); cellNum++) {
                Cell cell = row.getCell(cellNum);
                //把单元格的内容转换为字符串
                if (ToolUtil.isNotEmpty(cell)) {
                    cell.setCellType(CellType.STRING);
                }
            }
            String tiancai = row.getCell(2) == null ? "" : row.getCell(2).getStringCellValue();//天财店名
            String yaoma = row.getCell(3) == null ? "" : row.getCell(3).getStringCellValue();//妖码
            String yyjl = row.getCell(6) == null ? "" : row.getCell(6).getStringCellValue();//营运经理
            String dm = row.getCell(4) == null ? "" : row.getCell(4).getStringCellValue();//店名
            String gcAddress = row.getCell(5) == null ? "" : row.getCell(5).getStringCellValue();//工程地址
            String mt = row.getCell(8) == null ? "" : row.getCell(8).getStringCellValue();//美团店名
            String elm = row.getCell(9) == null ? "" : row.getCell(9).getStringCellValue();//饿了么店名

            String spjyxkzrq = row.getCell(10) == null ? "" : row.getCell(10).getStringCellValue().trim();//食品经营许可证截止日期

            if (ToolUtil.isNotEmpty(spjyxkzrq) && !spjyxkzrq.contains("-")){
                Calendar calendar = new GregorianCalendar(1900,0,-1);
                Date d = calendar.getTime();
                Date date = DateUtils.addDays(d, Integer.valueOf(spjyxkzrq));
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                spjyxkzrq = simpleDateFormat.format(date);
            }

            String yyzzmc = row.getCell(11) == null ? "" : row.getCell(11).getStringCellValue();//营业执照名称
            String shxydm = row.getCell(12) == null ? "" : row.getCell(12).getStringCellValue();//统一社会信用代码
            String yyzzdz = row.getCell(13) == null ? "" : row.getCell(13).getStringCellValue(); //营业执照地址
            String yyzzfr = row.getCell(7) == null ? "" : row.getCell(7).getStringCellValue(); //法人姓名

            if (ToolUtil.isNotEmpty(yaoma) && ToolUtil.isNotEmpty(dm)){
                btySzgl.setTiancai(tiancai.trim());//去除前后空格
                btySzgl.setYaoma(yaoma.trim());
                btySzgl.setYyjl(yyjl.trim());
                btySzgl.setDm(dm.trim());
                btySzgl.setMt(mt.trim());
                btySzgl.setElm(elm.trim());
                btySzgl.setYyzzmc(yyzzmc.trim());
                btySzgl.setShxydm(shxydm.trim());
                btySzgl.setYyzzdz(yyzzdz.trim());
                btySzgl.setCreateUser(createUser);
                btySzgl.setCreateTime(createTime);
                btySzgl.setYyzzfr(yyzzfr.trim());
                btySzgl.setSpjyxkzrq(spjyxkzrq);
                btySzgl.setGcAddress(gcAddress.trim());

                list.add(btySzgl);
                btySzgl = new BtySzgl();
            }
        }

        if(ToolUtil.isNotEmpty(list)){
            //查询数据库中是否存在此数据
            List<String> conList = baseMapper.getByYmList(list);
            List<BtySzgl> szList = new ArrayList<>();
            if (ToolUtil.isNotEmpty(conList)){
                for (BtySzgl szgl : list) {
                    //数据库不存在，新增
                    if (!conList.contains(szgl.getYaoma())){
                        notNull = this.save(szgl);
                    }else {
                        szgl.setUpdateTime(createTime);
                        szList.add(szgl);
//                        notNull = baseMapper.updateByYm(szgl);
                    }
                }
                //数据库存在，修改
                for(int i = 0; i < szList.size();){
                    int i2 = (i + 130);
                    i2 = i2 > szList.size() ? szList.size() : i2;
                    List<BtySzgl> sub = szList.subList(i, i2);
                    //修改
                    notNull = baseMapper.updateByYmList(sub);
                    i = i2;
                }
            }
            //查询状态为未修改过的店进行同步
            List<BtySzgl> staList = baseMapper.getBtSta(list);
            if (ToolUtil.isNotEmpty(staList)){
                //保存工程中工程地址、食品经营许可图片、营业执照图片、食品经营许可截止日期、法人身份证照片
                saveGc(staList);
            }
            //同步省市
            baseMapper.saveArea();
            //同步法人姓名(同步excel法人姓名为空的数据)
            baseMapper.saveFr();

            //同步法人和食品经营许可截止日期同步到安全基金和通讯录中
            //获取法人和食品经营许可证信息
            List<Map> txlList = baseMapper.getList();
            if (ToolUtil.isNotEmpty(txlList)){
                this.syncTxl(txlList);
            }
        }

        return notNull;
    }



//    public Boolean batchImport(String fileName, MultipartFile file) throws Exception{
//
//        boolean notNull = false;
//        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
//            throw new Exception("上传文件格式不正确");
//        }
//
//        boolean isExcel2003 = true;//Excel2003
//        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
//            isExcel2003 = false;
//        }
//
//        InputStream is = file.getInputStream();
//        Workbook wb = null;
//        if (isExcel2003) {
//            wb = new HSSFWorkbook(is);
//        } else {
//            wb = new XSSFWorkbook(is);
//        }
//
//        //TODO-1 默认就一个sheet
//        Sheet sheet = wb.getSheetAt(0);
//
//        List<BtySzgl> list = new ArrayList();
//        BtySzgl btySzgl = new BtySzgl();
//        Long createUser = LoginContextHolder.getContext().getUserId();//创建者
//        Date createTime = new Date();//创建时间
//
//        //循环行row
//        int lastRowNum = sheet.getLastRowNum() - 1;
//        for (int r = 1; r <= lastRowNum; r++) {
//            Row row = sheet.getRow(r);
//            if (row == null) {
//                continue;
//            }
//            //循环单元格cell
//            for (int cellNum = 0; cellNum <= row.getLastCellNum(); cellNum++) {
//                Cell cell = row.getCell(cellNum);
//                //把单元格的内容转换为字符串
//                if (ToolUtil.isNotEmpty(cell)) {
//                    cell.setCellType(CellType.STRING);
//                }
//            }
//            String tiancai = row.getCell(0) == null ? "" : row.getCell(0).getStringCellValue();//天财店名
//            String yaoma = row.getCell(1) == null ? "" : row.getCell(1).getStringCellValue();//妖码
//            String yyjl = row.getCell(2) == null ? "" : row.getCell(2).getStringCellValue();//营运经理
//            String dm = row.getCell(3) == null ? "" : row.getCell(3).getStringCellValue();//店名
//            String mt = row.getCell(4) == null ? "" : row.getCell(4).getStringCellValue();//美团店名
//            String elm = row.getCell(5) == null ? "" : row.getCell(5).getStringCellValue();//饿了么店名
//            String yyzzmc = row.getCell(6) == null ? "" : row.getCell(6).getStringCellValue();//营业执照名称
//            String shxydm = row.getCell(7) == null ? "" : row.getCell(7).getStringCellValue();//统一社会信用代码
//            String yyzzdz = row.getCell(8) == null ? "" : row.getCell(8).getStringCellValue(); //营业执照地址
//
//            if (ToolUtil.isNotEmpty(yaoma) && ToolUtil.isNotEmpty(dm)){
//                btySzgl.setTiancai(tiancai.trim());//去除前后空格
//                btySzgl.setYaoma(yaoma.trim());
//                btySzgl.setYyjl(yyjl.trim());
//                btySzgl.setDm(dm.trim());
//                btySzgl.setMt(mt.trim());
//                btySzgl.setElm(elm.trim());
//                btySzgl.setYyzzmc(yyzzmc.trim());
//                btySzgl.setShxydm(shxydm.trim());
//                btySzgl.setYyzzdz(yyzzdz.trim());
//                btySzgl.setCreateUser(createUser);
//                btySzgl.setCreateTime(createTime);
//
//                list.add(btySzgl);
//                btySzgl = new BtySzgl();
//            }
//        }
//
//        if(ToolUtil.isNotEmpty(list)){
//            for (BtySzgl szgl : list) {
//                //查询数据库中是否存在此数据
//                int con = baseMapper.getByYm(szgl);
//                if (con == 0){
//                    notNull = this.save(szgl);
//                }else {
//                    notNull = baseMapper.updateByYm(szgl);
//                }
//            }
//            //查询状态为未修改过的店进行同步
//            List<BtySzgl> staList = baseMapper.getBtSta(list);
//            if (ToolUtil.isNotEmpty(staList)){
//                //保存工程中工程地址、食品经营许可图片、营业执照图片、食品经营许可截止日期、法人身份证照片
//                saveGc(staList);
//            }
//            //同步省市
//            baseMapper.saveArea();
//            //同步法人姓名
//            baseMapper.saveFr();
//        }
//
//        return notNull;
//    }

    public void saveGc(List<BtySzgl> list){
        //获取工程中工程地址、食品经营许可图片、营业执照图片、食品经营许可截止日期、法人身份证照片
        List<Map> maps = projectMapper.getGc(list);
        BtySzgl btySzgl = new BtySzgl();
        List<BtySzgl> szglList = new ArrayList<>();
        //获取工程地址为空的店
        List<BtySzgl> addressList = baseMapper.getAddress();
        //食品经营许可截止日期
        List<BtySzgl> rqList = baseMapper.getRq();

        for (Map map : maps) {
            String yaoma = map.get("yaoma").toString();
            //妖码相等
            if (list.stream().filter(w -> w.getYaoma().equals(yaoma)).findAny().isPresent()){
//                btySzgl.setGcAddress(ToolUtil.isEmpty(map.get("address")) ? "" : map.get("address").toString());
                btySzgl.setSpjyxkz(ToolUtil.isEmpty(map.get("sp")) ? "" : map.get("sp").toString());
                btySzgl.setYyzz(ToolUtil.isEmpty(map.get("yyzz")) ? "" : map.get("yyzz").toString());
//                btySzgl.setSpjyxkzrq(ToolUtil.isEmpty(map.get("rq")) ? "" : map.get("rq").toString());
                btySzgl.setFrCard(ToolUtil.isEmpty(map.get("fr")) ? "" : map.get("fr").toString());
                btySzgl.setYaoma(yaoma);

                szglList.add(btySzgl);
                btySzgl = new BtySzgl();
            }

            //修改工程地址
            if (addressList.stream().filter(w -> w.getYaoma().equals(yaoma)).findAny().isPresent()){
                btySzgl.setGcAddress(ToolUtil.isEmpty(map.get("address")) ? "" : map.get("address").toString());
                btySzgl.setYaoma(yaoma);
                baseMapper.updateByYm(btySzgl);
                btySzgl = new BtySzgl();
            }

            //修改食品经营许可证截止日期
            if (rqList.stream().filter(w -> w.getYaoma().equals(yaoma)).findAny().isPresent()){
                btySzgl.setSpjyxkzrq(ToolUtil.isEmpty(map.get("rq")) ? "" : map.get("rq").toString());
                btySzgl.setYaoma(yaoma);
                baseMapper.updateByYm(btySzgl);
                btySzgl = new BtySzgl();
            }
        }
        if (ToolUtil.isNotEmpty(szglList)){
            //每150条保存一次
            for(int i = 0; i < szglList.size();){
                int i2 = (i + 150);
                i2 = i2 > szglList.size() ? szglList.size() : i2;
                List<BtySzgl> sub = szglList.subList(i, i2);
                //修改
                this.baseMapper.updateList(sub);
                i = i2;
            }
        }

    }

    /**
     * 导出excel
     * @param btySzglParam
     * @return
     */
    @Override
    public void expList(BtySzglParam btySzglParam, HttpServletResponse response) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String number = sdf.format(new Date());
        // 查询数据
        List<BtySzglResult> list = baseMapper.expList(btySzglParam);

        String fileName = number;
        String path = "D:\\" + "xls\\";
        File f = new File(path);
        if (!f.exists()) {
            f.mkdirs(); //创建目录
        }
        String url = path + fileName + ".xls";
        try {
            //map数据
            List<String[]> dataset = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                String[] arr = new String[14];
                arr[0] = list.get(i).getFirstArea() == null ? "" : list.get(i).getFirstArea();
                arr[1] = list.get(i).getSecondArea() == null ? "" : list.get(i).getSecondArea();
                arr[2] = list.get(i).getTiancai() == null ? "" : list.get(i).getTiancai();
                arr[3] = list.get(i).getYaoma() == null ? "" : list.get(i).getYaoma();
                arr[4] = list.get(i).getDm() == null ? "" : list.get(i).getDm();
                arr[5] = list.get(i).getGcAddress() == null ? "" : list.get(i).getGcAddress();
                arr[6] = list.get(i).getYyjl() == null ? "" : list.get(i).getYyjl();
                arr[7] = list.get(i).getYyzzfr() == null ? "" : list.get(i).getYyzzfr();
                arr[8] = list.get(i).getMt() == null ? "" : list.get(i).getMt();
                arr[9] = list.get(i).getElm() == null ? "" : list.get(i).getElm();
                arr[10] = list.get(i).getSpjyxkzrq() == null ? "" : list.get(i).getSpjyxkzrq();
                arr[11] = list.get(i).getYyzzmc() == null ? "" : list.get(i).getYyzzmc();
                arr[12] = list.get(i).getShxydm() == null ? "" : list.get(i).getShxydm();
                arr[13] = list.get(i).getYyzzdz() == null ? "" : list.get(i).getYyzzdz();
                dataset.add(arr);
            }
            //外卖导出表头
            String[] handers1 = {"一级区域", "二级区域", "天财店名", "妖码", "工程店名", "工程地址", "营运经理", "法人姓名", "美团店名", "饿了么店名", "食品经营许可证截止日期", "营业执照名称", "统一社会信用代码", "营业执照地址"};
            //对象
            ExcelExp fymx = new ExcelExp("通讯录", handers1, dataset);
            List<ExcelExp> mysheet = new ArrayList<>();
            mysheet.add(fymx);
            //生成sheet
            ExcelUtil.exportManySheetExcel(url, mysheet);
            //下载sheet
            ExcelUtil.getExcel(url, fileName, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 营运经理列表
     * @return
     */
    @Override
    public ResponseData yyjlList() {
        List<Map> list = areaMapper.yyjlList();
        for (Map map : list) {
            if (map.get("yyjl").equals("孙课=姚翠芳")){
                map.put("yyjl", "孙课");
            }
        }
        Map map = new HashMap<>();
        map.put("yyjl","张少将");
        if (!list.contains(map)){
            list.add(map);
        }
        return ResponseData.success(list);
    }

    /**
     * 批量下载图片
     * @param ids
     * @param request
     * @param response
     */
    @Override
    public void btnDown(String ids, HttpServletRequest request, HttpServletResponse response) {
        try {
            String id[] = ids.split(",");
            //查图片
            List<BtySzgl> pics = this.baseMapper.selectPic(id);

            //多个图片下载地址
            File fileMemu = new File("D:/szgl/sztp/");//输入要删除文件目录的绝对路径
            deleteFile(fileMemu);

            //多个图片下载地址
            for (int i = 0; i < pics.size(); i++) {

                //营业执照
                if (ToolUtil.isNotEmpty(pics.get(i).getYyzz())){
                    String yyzz = pics.get(i).getYyzz();
                    if (!yyzz.contains("http")){
                        yyzz = "https://rs.bantianyaozg.com" + yyzz;
//                        yyzz = "http://http://192.168.188.178:82" + yyzz;
                    }
                    if (yyzz.contains(" ")){
                        yyzz = yyzz.replaceAll(" ", "%20");
                    }
                    //根据图片地址构建URL
                    URL url = new URL(yyzz);//营业执照
                    URLConnection conn = url.openConnection();
                    conn.setReadTimeout(10000);
                    conn.setConnectTimeout(10000);
                    conn.connect();
                    DataInputStream dataInputStream = new DataInputStream(conn.getInputStream());
                    //创建目录和图片
                    File pathFile = new File("D:/szgl/sztp/" + pics.get(i).getDm());
                    File file = new File("D:/szgl/sztp/" + pics.get(i).getDm() + File.separator + "营业执照" + i + ".jpg");
                    if (!pathFile.exists()) {
                        pathFile.mkdirs();
                        file.createNewFile();
                    }
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    //通过流复制图片
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = dataInputStream.read(buffer)) > 0) {
                        output.write(buffer, 0, length);
                    }
                    fileOutputStream.write(output.toByteArray());
                    dataInputStream.close();
                    fileOutputStream.close();

                    //删除服务器上的临时文件
                    File deleteFile = new File(pics.get(i).getDm());
                    deleteFile.delete();
                }

                //食品经营许可证
                if (ToolUtil.isNotEmpty(pics.get(i).getSpjyxkz())){
                    String spjyxkz = pics.get(i).getSpjyxkz();
                    if (!spjyxkz.contains("http")){
                        spjyxkz = "https://rs.bantianyaozg.com" + spjyxkz;
//                        spjyxkz = "http://http://192.168.188.178:82" + spjyxkz;
                    }
                    if (spjyxkz.contains(" ")){
                        spjyxkz = spjyxkz.replaceAll(" ", "%20");
                    }
                    //根据图片地址构建URL
                    URL url = new URL(spjyxkz);//食品经营许可证
                    URLConnection conn = url.openConnection();
                    conn.setReadTimeout(10000);
                    conn.setConnectTimeout(10000);
                    conn.connect();
                    DataInputStream dataInputStream = new DataInputStream(conn.getInputStream());
                    //创建目录和图片
                    File pathFile = new File("D:/szgl/sztp/" + pics.get(i).getDm());//C:\Users\csh\Desktop
                    File file = new File("D:/szgl/sztp/" + pics.get(i).getDm() + File.separator + "食品经营许可证" + i + ".jpg");
                    if (!pathFile.exists()) {
                        pathFile.mkdirs();
                        file.createNewFile();
                    }
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    //通过流复制图片
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    ByteArrayOutputStream output = new ByteArrayOutputStream();
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = dataInputStream.read(buffer)) > 0) {
                        output.write(buffer, 0, length);
                    }
                    fileOutputStream.write(output.toByteArray());
                    dataInputStream.close();
                    fileOutputStream.close();
                }

                //法人身份证
                if (ToolUtil.isNotEmpty(pics.get(i).getFrCard())){
                    String frCards = pics.get(i).getFrCard();
                    if (frCards.contains(",")){
                        int num = 1;
                        for (String frCard: frCards.split(",")) {

                            if (!frCard.contains("http")){
                                frCard = "https://rs.bantianyaozg.com" + frCard;
//                        frCard = "http://http://192.168.188.178:82" + frCard;
                            }
                            if (frCard.contains(" ")){
                                frCard = frCard.replaceAll(" ", "%20");
                            }
                            //根据图片地址构建URL
                            URL url = new URL(frCard);//食品经营许可证
                            URLConnection conn = url.openConnection();
                            conn.setReadTimeout(10000);
                            conn.setConnectTimeout(10000);
                            conn.connect();
                            DataInputStream dataInputStream = new DataInputStream(conn.getInputStream());
                            //创建目录和图片
                            File pathFile = new File("D:/szgl/sztp/" + pics.get(i).getDm());//C:\Users\csh\Desktop
                            File file = new File("D:/szgl/sztp/" + pics.get(i).getDm() + File.separator + "法人身份证" + "(" + num + ")" + ".jpg");
                            if (!pathFile.exists()) {
                                pathFile.mkdirs();
                                file.createNewFile();
                            }
                            if (!file.exists()) {
                                file.createNewFile();
                            }
                            //通过流复制图片
                            FileOutputStream fileOutputStream = new FileOutputStream(file);
                            ByteArrayOutputStream output = new ByteArrayOutputStream();
                            byte[] buffer = new byte[1024];
                            int length;
                            while ((length = dataInputStream.read(buffer)) > 0) {
                                output.write(buffer, 0, length);
                            }
                            fileOutputStream.write(output.toByteArray());
                            dataInputStream.close();
                            fileOutputStream.close();
                            num++;
                        }
                    }else {
                        if (!frCards.contains("http")){
                            frCards = "https://rs.bantianyaozg.com" + frCards;
//                        frCard = "http://http://192.168.188.178:82" + frCard;
                        }
                        if (frCards.contains(" ")){
                            frCards = frCards.replaceAll(" ", "%20");
                        }
                        //根据图片地址构建URL
                        URL url = new URL(frCards);//食品经营许可证
                        URLConnection conn = url.openConnection();
                        conn.setReadTimeout(10000);
                        conn.setConnectTimeout(10000);
                        conn.connect();
                        DataInputStream dataInputStream = new DataInputStream(conn.getInputStream());
                        //创建目录和图片
                        File pathFile = new File("D:/szgl/sztp/" + pics.get(i).getDm());//C:\Users\csh\Desktop
                        File file = new File("D:/szgl/sztp/" + pics.get(i).getDm() + File.separator + "法人身份证" + i + ".jpg");
                        if (!pathFile.exists()) {
                            pathFile.mkdirs();
                            file.createNewFile();
                        }
                        if (!file.exists()) {
                            file.createNewFile();
                        }
                        //通过流复制图片
                        FileOutputStream fileOutputStream = new FileOutputStream(file);
                        ByteArrayOutputStream output = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int length;
                        while ((length = dataInputStream.read(buffer)) > 0) {
                            output.write(buffer, 0, length);
                        }
                        fileOutputStream.write(output.toByteArray());
                        dataInputStream.close();
                        fileOutputStream.close();
                    }
                }

            }

            File file1 = new File("D:/szgl/sztp/");//创建文件目录的绝对路径
            if (!file1.exists()){
                file1.mkdir();
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void deleteFile(File file){
        //判断文件不为null或文件目录存在
        if (file == null || !file.exists()){
            System.out.println("文件删除失败,请检查文件路径是否正确");
            return;
        }
        //取得这个目录下的所有子文件对象
        File[] files = file.listFiles();
        //遍历该目录下的文件对象
        for (File f: files){
            //打印文件名
            String name = file.getName();
            System.out.println(name);
            //判断子目录是否存在子目录,如果是文件则删除
            if (f.isDirectory()){
                deleteFile(f);
            }else {
                f.delete();
            }
        }
        //删除空文件夹  for循环已经把上一层节点的目录清空。
        file.delete();
    }

    /**
     * 同步法人和食品经营许可截止日期同步到安全基金和通讯录中
     */
    @Override
    public void syncTxl(List<Map> list) {
        //批量修改通讯录中法人和食品经营许可截止日期
        for(int i = 0; i < list.size();){
            int i2 = (i + 150);
            i2 = i2 > list.size() ? list.size() : i2;
            List<Map> sub = list.subList(i, i2);
            //修改通讯录中信息
            btyTxlService.editTxl(sub);
            i = i2;
        }
    }

    private Serializable getKey(BtySzglParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BtySzgl getOldEntity(BtySzglParam param) {
        return this.getById(getKey(param));
    }

    private BtySzgl getEntity(BtySzglParam param) {
        BtySzgl entity = new BtySzgl();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
